﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace DIYS
{
    public class BTCommands
    {
        private string FILEPATH = Environment.CurrentDirectory + @"\BTCommands.xml";

        public BTCommands()
        {

        }

        public string GetAllCommands()
        {
            string commands = "\n>> DIYS COMMANDS <<\n";

            var result = from item in XElement.Load(FILEPATH).Elements("Command")
                         select item;

            foreach (var item in result)
            {
                commands += "Code: " + (string)item.Element("Code").Value + Environment.NewLine;
                commands += "Description: " + (string)item.Element("Description").Value + Environment.NewLine;
                commands += Environment.NewLine;
            }

            return commands;
        }


        public string GetCommandDescription(string cmd)
        {
            var result = from item in XElement.Load(FILEPATH).Elements("Command")
                         where (string)item.Element("Code").Value == cmd
                         select (string)item.Element("Description");
            
            if (result.Count() == 1)
            {
                return (string)result.First();
            }
            else
            {
                return "Description not found";
            }
        }

        public void ParseCommand(string command)
        {
            command = command.Trim();
            string code = command.Substring(0, 1);
            string value = command.Substring(1, command.Length-1);
            string desc = "";

            
            if (code.Equals("T"))
                return;
            else
            {
                desc = GetCommandDescription(code);

                if (desc.Equals("Description not found"))
                    throw new CommandParseException(command + " Command not found");


                try
                {
                    if (Int32.Parse(value) < 0)
                        throw new CommandParseException(command + " Negative number not allowed");
                    
                }
                catch (FormatException)
                {
                    throw new CommandParseException(command + " Value not accepted");
                }

                


                
                    
            }
        }

    }

    public class CommandParseException : Exception
    {
        public CommandParseException(string message)
            : base(message)
        {

        }
    }

}
